package bb.lanxing.activity.routebook;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.view.ViewCompat;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.github.mikephil.charting.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.base.BaseActivity;
import bb.lanxing.adapter.LocationSearchAdapter;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.util.BiCiCoorConverter;
import bb.lanxing.util.DensityUtil;
import bb.lanxing.util.MapUtil;
import bb.lanxing.util.ui.InputHelper;
import bb.lanxing.view.BiciAlertDialogBuilder;

public class RouteBookPositionChooseActivity extends BaseActivity {
    private static final int MSG_REFRESH_UI = 2;
    private static final int MSG_REQUEST_GEO_ADDRESS = 1;
    private String address;
    private TextView addressView;
    private BaiduMap baiduMap;
    private ImageView centerLocationIcon;
    private GeoCoder geoCoder;
    private View mConfirmBtn;
    private View mSearchBtn;
    private TextureMapView mapView;
    private PoiSearch poiSearch;
    private EditText searchText;
    private DisplayPoint startPoint;
    private int style;
    private List<PoiInfo> poiInfoList = new ArrayList<>();
    private LatLng goToLatLng = null;
    private final OnGetGeoCoderResultListener onGetGeoCoderResultListener = new OnGetGeoCoderResultListener() {
        @Override
        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
        }

        @Override
        public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
            if (geoCodeResult.error == SearchResult.ERRORNO.NO_ERROR) {
                geoCodeResult.getAddress();
                final LatLng location = geoCodeResult.getLocation();
                RouteBookPositionChooseActivity.this.handler.post(() -> RouteBookPositionChooseActivity.this.initPoi(location));
                return;
            }
            RouteBookPositionChooseActivity.this.dismissLoadingDialog();
            App.getContext().showMessage(R.string.toast_find_no_result);
        }
    };
    OnGetPoiSearchResultListener onGetPoiSearchResultListener = new OnGetPoiSearchResultListener() {
        @Override
        public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
        }

        @Override
        public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {
        }

        @Override
        public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {
        }

        @Override
        public void onGetPoiResult(PoiResult poiResult) {
            RouteBookPositionChooseActivity.this.dismissLoadingDialog();
            if (poiResult.error == SearchResult.ERRORNO.NO_ERROR) {
                List<PoiInfo> allPoi = poiResult.getAllPoi();
                if (allPoi != null) {
                    RouteBookPositionChooseActivity.this.poiInfoList.clear();
                    RouteBookPositionChooseActivity.this.poiInfoList.addAll(allPoi);
                }
                RouteBookPositionChooseActivity.this.showLocationSearchResultDialog();
                return;
            }
            App.getContext().showMessage(R.string.toast_find_no_result);
        }
    };
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message message) {
            int i = message.what;
            if (i == 1) {
                requestGeoAddress((LatLng) message.obj);
            } else if (i != 2) {
            } else {
                refreshMapUI();
                setAddress();
            }
        }
    };

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_lushu_start_position_choose);
        bindView(getWindow().getDecorView());
        setupActionBar(true);
        int intExtra = getIntent().getIntExtra("style", 0);
        this.style = intExtra;
        if (intExtra == 1) {
            setTitle(R.string.lushu_point_select_title_start);
            this.searchText.setHint(R.string.lushu_point_select_hint_start);
        } else if (intExtra == 2) {
            setTitle(R.string.lushu_point_select_title_stop);
            this.searchText.setHint(R.string.lushu_point_select_hint_stop);
        } else {
            toast(R.string.lushu_point_select_toast_error);
        }
        initView();
        DisplayPoint displayPoint = new DisplayPoint(SharedManager.getInstance().getCurLatLngWithMP());
        this.startPoint = displayPoint;
        displayPoint.setType(1);
        MapUtil.setMapStatus(this.baiduMap, MapStatusUpdateFactory.newLatLngZoom(BiCiCoorConverter.earth2Baidu(this.startPoint.getLatLng()), 16.0f));
        selectItem();
        this.startPoint.reverseGeoCode();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mapView.onDestroy();
        releasePoiSearch();
        Handler handler = this.handler;
        if (handler != null) {
            handler.removeMessages(1);
            this.handler.removeMessages(2);
        }
    }

    private void onSearchClick() {
        InputHelper.hideSoftInput(this.searchText);
        String obj = this.searchText.getText().toString();
        if (TextUtils.isEmpty(obj)) {
            App.getContext().showMessage(R.string.lushu_toast_input_search);
            return;
        }
        initGeoCoder();
        geoCodeSearch(obj);
    }

    private void initGeoCoder() {
        GeoCoder newInstance = GeoCoder.newInstance();
        this.geoCoder = newInstance;
        newInstance.setOnGetGeoCodeResultListener(this.onGetGeoCoderResultListener);
        PoiSearch newInstance2 = PoiSearch.newInstance();
        this.poiSearch = newInstance2;
        newInstance2.setOnGetPoiSearchResultListener(this.onGetPoiSearchResultListener);
    }

    private void releasePoiSearch() {
        PoiSearch poiSearch = this.poiSearch;
        if (poiSearch != null) {
            poiSearch.destroy();
            this.poiSearch = null;
        }
        GeoCoder geoCoder = this.geoCoder;
        if (geoCoder != null) {
            geoCoder.destroy();
            this.geoCoder = null;
        }
    }

    public void initPoi(LatLng latLng) {
        PoiNearbySearchOption poiNearbySearchOption = new PoiNearbySearchOption();
        poiNearbySearchOption.location(latLng);
        poiNearbySearchOption.keyword(this.searchText.getText().toString());
        poiNearbySearchOption.radius(1000);
        poiNearbySearchOption.pageCapacity(50);
        poiNearbySearchOption.pageNum(0);
        this.poiSearch.searchNearby(poiNearbySearchOption);
    }

    private void geoCodeSearch(String str) {
        if (this.geoCoder == null) {
            return;
        }
        showMyProgressDialog(R.string.dialog_searching);
        String str2 = !this.poiInfoList.isEmpty() ? this.poiInfoList.get(0).city : "";
        if (TextUtils.isEmpty(str2)) {
            str2 = SharedManager.getInstance().getCurCityWithMP();
        }
        if (TextUtils.isEmpty(str2)) {
            str2 = "上海";
        }
        try {
            this.geoCoder.geocode(new GeoCodeOption().address(str).city(str2));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showLocationSearchResultDialog() {
        TextView textView = new TextView(this);
        textView.setBackgroundColor(ViewCompat.MEASURED_STATE_MASK);
        int i = this.style;
        if (i == 1) {
            textView.setText(R.string.lushu_point_select_dialog_title_select_start);
        } else if (i == 2) {
            textView.setText(R.string.lushu_point_select_dialog_title_select_stop);
        } else {
            textView.setText(R.string.lushu_point_select_dialog_title_please_select);
        }
        textView.setTextColor(-1);
        textView.setTextSize(0, getResources().getDimensionPixelOffset(R.dimen.custom_dialog_title_text_size));
        textView.setHeight(getResources().getDimensionPixelOffset(R.dimen.custom_dialog_title_bar_height));
        textView.setGravity(17);
        new BiciAlertDialogBuilder(this).setCustomTitle(textView).setCancelable(true).setSingleChoiceItems(new LocationSearchAdapter(this, this.poiInfoList), -1, (dialogInterface, i2) -> {
            if (startPoint.getStatus() != 2) {
                startPoint.setStatus(2);
                refreshMapUI();
            }
            PoiInfo poiInfo = poiInfoList.get(i2);
            moveMapToLatlng(poiInfo.location);
            goToLatLng = BiCiCoorConverter.baidu2Earth(poiInfo.location);
            if (handler != null) {
                handler.post(() -> centerTo(goToLatLng));
                Message obtainMessage = handler.obtainMessage(1, goToLatLng);
                handler.removeMessages(1);
                handler.sendMessage(obtainMessage);
            }
            setAddress();
            dialogInterface.dismiss();
        }).show();
    }

    public void moveMapToLatlng(LatLng latLng) {
        MapUtil.setMapStatus(this.baiduMap, MapStatusUpdateFactory.newLatLngZoom(latLng, 17.0f));
    }

    private void onClickConfirmBtn() {
        Intent intent = new Intent();
        intent.putExtra("address", this.address);
        intent.putExtra("lat", this.startPoint.getLatitude());
        intent.putExtra("lng", this.startPoint.getLongitude());
        setResult(-1, intent);
        finish();
    }

    public void initView() {
        this.mapView.showScaleControl(true);
        this.mapView.setClickable(true);
        this.mapView.showZoomControls(false);
        BaiduMap map = this.mapView.getMap();
        this.baiduMap = map;
        map.setOnMapStatusChangeListener(new AnonymousClass4());
    }

    public class AnonymousClass4 implements BaiduMap.OnMapStatusChangeListener {
        @Override
        public void onMapStatusChange(MapStatus mapStatus) {
        }

        @Override
        public void onMapStatusChangeStart(MapStatus mapStatus, int i) {
        }

        @Override
        public void onMapStatusChangeStart(MapStatus mapStatus) {
            runOnUiThread(() -> runOnUiThread(() -> {
                if (handler != null) {
                    handler.removeMessages(1);
                }
                if (startPoint.getStatus() == 0 || startPoint.getStatus() == 2) {
                    return;
                }
                startPoint.setStatus(2);
                refreshMapUI();
            }));
        }

        @Override
        public void onMapStatusChangeFinish(final MapStatus mapStatus) {
            runOnUiThread(() -> {
                if (startPoint.getStatus() == 0) {
                    return;
                }
                if (startPoint.getStatus() == 2) {
                    startPoint.setStatus(3);
                    refreshMapUI();
                    setAddress();
                }
                if (handler != null) {
                    Message obtainMessage = handler.obtainMessage(1, BiCiCoorConverter.baidu2Earth(mapStatus.target));
                    handler.removeMessages(1);
                    handler.sendMessageDelayed(obtainMessage, 50L);
                }
            });
        }
    }

    public void refreshMapUI() {
        this.centerLocationIcon.setImageResource(this.startPoint.getStatus() == 3 ? R.drawable.ic_lushu_edit_map_waypoint : R.drawable.ic_lushu_edit_map_waypoint_up);
        this.centerLocationIcon.setPadding(0, 0, 0, DensityUtil.dp2px(this.startPoint.getStatus() == 3 ? 39.0f : 52.0f));
    }

    public void setAddress() {
        String address = this.startPoint.getAddress();
        this.address = address;
        if (TextUtils.isEmpty(address)) {
            this.addressView.setVisibility(View.GONE);
            return;
        }
        this.addressView.setVisibility(View.VISIBLE);
        this.addressView.setText(this.address);
    }

    private void selectItem() {
        DisplayPoint displayPoint = this.startPoint;
        displayPoint.setStatus(displayPoint.getStatus() != 0 ? 0 : 1);
        if (this.startPoint.getStatus() == 1) {
            centerTo(this.startPoint.getLatLng());
        }
        refreshMapUI();
    }

    public void centerTo(LatLng latLng) {
        if (latLng.latitude <= Utils.DOUBLE_EPSILON || latLng.longitude <= Utils.DOUBLE_EPSILON) {
            return;
        }
        MapUtil.setMapStatus(this.baiduMap, MapStatusUpdateFactory.newLatLng(BiCiCoorConverter.earth2Baidu(latLng)));
    }

    public void requestGeoAddress(LatLng latLng) {
        setMarkerPositon(latLng);
        this.startPoint.setLatLng(latLng);
        this.startPoint.reverseGeoCode();
    }

    private void setMarkerPositon(LatLng latLng) {
        this.startPoint.setMarkerPosition(BiCiCoorConverter.earth2Baidu(latLng));
    }

    private void bindView(View view) {
        this.mapView = view.findViewById(R.id.mapView);
        this.addressView = view.findViewById(R.id.addressView);
        this.searchText = view.findViewById(R.id.searchText);
        this.centerLocationIcon = view.findViewById(R.id.centerLocationIcon);
        this.mSearchBtn = view.findViewById(R.id.searchBtn);
        this.mConfirmBtn = view.findViewById(R.id.confirmBtn);
        this.mSearchBtn.setOnClickListener(RouteBookPositionChooseActivity.this::m258xc68e6dd8);
        this.mConfirmBtn.setOnClickListener(RouteBookPositionChooseActivity.this::m259xc61807d9);
    }

    public void m258xc68e6dd8(View view) {
        onSearchClick();
    }

    public void m259xc61807d9(View view) {
        onClickConfirmBtn();
    }

    public class DisplayPoint {
        public static final int STATUS_NONE = 0;
        public static final int STATUS_SEARCHED = 3;
        public static final int STATUS_SEARCHING = 2;
        public static final int STATUS_SELECTED = 1;
        public static final int TYPE_START = 1;
        public static final int TYPE_WAY = 3;
        private String address;
        private String content;
        private GeoCoder geoCoder;
        private String image;
        private double latitude;
        private double longitude;
        private Marker marker;
        private String title;
        private boolean isCheckPoint = false;
        private int type = 3;
        private int status = 0;

        public DisplayPoint(LatLng latLng) {
            this.latitude = latLng.latitude;
            this.longitude = latLng.longitude;
            initGeoCoder();
        }

        private void initGeoCoder() {
            GeoCoder newInstance = GeoCoder.newInstance();
            this.geoCoder = newInstance;
            newInstance.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
                @Override
                public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
                }

                @Override
                public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
                    if (DisplayPoint.this.status != 0) {
                        DisplayPoint.this.status = 3;
                    }
                    DisplayPoint.this.address = reverseGeoCodeResult.getAddress();
                    if (TextUtils.isEmpty(DisplayPoint.this.address)) {
                        DisplayPoint.this.address = "已设置";
                    } else if (TextUtils.isEmpty(DisplayPoint.this.content)) {
                        DisplayPoint displayPoint = DisplayPoint.this;
                        displayPoint.content = displayPoint.address;
                    }
                    if (handler != null) {
                        handler.sendEmptyMessage(2);
                    }
                }
            });
        }

        public void reverseGeoCode() {
            if (isValid()) {
                LatLng earth2Baidu = BiCiCoorConverter.earth2Baidu(getLatLng());
                ReverseGeoCodeOption reverseGeoCodeOption = new ReverseGeoCodeOption();
                reverseGeoCodeOption.location(earth2Baidu);
                this.geoCoder.reverseGeoCode(reverseGeoCodeOption);
            }
        }

        public void release() {
            removeMarker();
            GeoCoder geoCoder = this.geoCoder;
            if (geoCoder != null) {
                geoCoder.destroy();
                this.geoCoder = null;
            }
        }

        public boolean isValid() {
            return (this.latitude == Utils.DOUBLE_EPSILON || this.longitude == Utils.DOUBLE_EPSILON) ? false : true;
        }

        public double getLatitude() {
            return this.latitude;
        }

        public double getLongitude() {
            return this.longitude;
        }

        public LatLng getLatLng() {
            return new LatLng(this.latitude, this.longitude);
        }

        public void setLatLng(double d, double d2) {
            this.latitude = d;
            this.longitude = d2;
        }

        public void setLatLng(LatLng latLng) {
            this.latitude = latLng.latitude;
            this.longitude = latLng.longitude;
        }

        public String getAddress() {
            return this.address;
        }

        public void setAddress(String str) {
            this.address = str;
        }

        public String getTitle() {
            return this.title;
        }

        public void setTitle(String str) {
            this.title = str;
        }

        public String getContent() {
            return this.content;
        }

        public void setContent(String str) {
            this.content = str;
        }

        public String getImage() {
            return this.image;
        }

        public void setImage(String str) {
            this.image = str;
        }

        public Marker getMarker() {
            return this.marker;
        }

        public void setMarker(Marker marker) {
            this.marker = marker;
        }

        public void setMarkerPosition(LatLng latLng) {
            try {
                Marker marker = this.marker;
                if (marker != null) {
                    marker.setPosition(latLng);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void removeMarker() {
            try {
                Marker marker = this.marker;
                if (marker != null) {
                    marker.remove();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public int getType() {
            return this.type;
        }

        public void setType(int i) {
            this.type = i;
        }

        public int getStatus() {
            return this.status;
        }

        public void setStatus(int i) {
            this.status = i;
        }
    }
}
